package com.interagriculture.controller;

import com.interagriculture.annotation.AdminVerify;
import com.interagriculture.common.CustomException;
import com.interagriculture.common.Result;
import com.interagriculture.entity.Admin;
import com.interagriculture.entity.AdminInfo;
import com.interagriculture.enums.ExceptionCodeEnum;
import com.interagriculture.service.AdminService;
import com.interagriculture.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * (Admin)表控制层
 *
 * @author makejava
 * @since 2024-11-09 17:57:59
 */
@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {
    /**
     * 服务对象
     */
    @Resource
    private AdminService adminService;

    /**
     * 查询自己信息
     * @return
     */
    @GetMapping("/findSelf")
    public Result<Admin> findSelf()
    {
        Admin admin = adminService.queryByAccount(ThreadLocalUtil.get().getAccount());
        admin.setPassword(null);
        return Result.ok(admin);
    }

    /**
     * 修改密码
     * @param admin
     * @return
     */
    @PostMapping("/update")
    @AdminVerify
    public Result update(@RequestBody Admin admin)
    {
        if(admin.getId()==null){
            throw new CustomException(ExceptionCodeEnum.ERROR_REQUEST);
        }
        if(admin.getPassword()==null || admin.getAccount()==null){
            throw new CustomException(ExceptionCodeEnum.PASSWORD_NOT_NULL);
        }
        Admin afterUpdate = adminService.update(admin);
        return Result.ok(afterUpdate);
    }

    /**
     * 删除成员
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @AdminVerify
    public Result delete(@RequestParam Integer id)
    {
        adminService.deleteById(id);
        return Result.ok();
    }

    /**
     * 添加管理员
     * @param admin
     * @return
     */
    @PostMapping("/save")
    @AdminVerify
    public Result save(@RequestBody Admin admin){
      if(admin.getId()!=null){
          throw new CustomException(ExceptionCodeEnum.ERROR_REQUEST);
      }
      adminService.insert(admin);
      return Result.ok();
    }
}

